package cn.deschen.common.config.mybatisplus;

import cn.deschen.common.config.security.UserInfoContext;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * @Author hanbin_chen
 * @Description 元对象字段填充控制器，实现公共字段自动写入
 * @DateTime 2021/6/4
 * @Version V1.0.0
 */
@Slf4j
public class CustomMetaObjectHandler implements MetaObjectHandler {

    /**
     * @param
     * @method 插入时自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {

        Long currentUserId = 0L;
        try {
            currentUserId = null != UserInfoContext.getCurrentUser() ? UserInfoContext.getCurrentUser().getId() : 0L;
        } catch (Exception e) {
            log.error("打印填充出现的异常={}",e);
        }
        this.setFieldValByName("createBy", currentUserId, metaObject);

        String createTimeField = "createTime";
        if(metaObject.hasGetter(createTimeField) && metaObject.getValue(createTimeField) == null) {
            this.setFieldValByName(createTimeField, LocalDateTime.now(), metaObject);
        }

        this.setFieldValByName("updateBy", currentUserId, metaObject);

        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);

        this.setFieldValByName("isDel", 0, metaObject);
    }

    /**
     * @param
     * @method 更新时自动填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Long currentUserId = 0L;
        try {
            currentUserId = null != UserInfoContext.getCurrentUser() ? UserInfoContext.getCurrentUser().getId() : 0L;
        } catch (Exception e) {
            log.info("打印填充出现的异常={}",e);
        }
        this.setFieldValByName("updateBy", currentUserId, metaObject);

        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
    }
}
